//
//  CCTools.m
//  Zhangda_new
//
//  Created by apple on 15/9/1.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "CCTools.h"
#import "ABTools.h"


@implementation CCTools
+ (void)JSONDataToDictionaryWithUrl:(NSString *)url
                          dictinory:(NSDictionary *)dictionary
                            success:(void (^)(id data))success
                               fail:(void (^)(NSError *error))fail
{
    AFHTTPRequestOperationManager *manager = [ABTools managerwithURL:url];
        [manager POST:url parameters:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (success) {
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    success(responseObject);
                }else{
                    NSData *doubi = responseObject;
                    NSString *shabi =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
                    
                    NSData *data1 = [shabi dataUsingEncoding:NSUTF8StringEncoding];
                    
                    NSError *error = nil;
                    id jsonObject = [NSJSONSerialization JSONObjectWithData:data1
                                                                    options:NSJSONReadingAllowFragments
                                                                      error:&error];
                    if (jsonObject == nil) {
                        shabi = [CCTools jsonpTojson:shabi];
                        NSData *data1 = [shabi dataUsingEncoding:NSUTF8StringEncoding];
                        
                        NSError *error = nil;
                        jsonObject = [NSJSONSerialization JSONObjectWithData:data1
                                                                     options:NSJSONReadingAllowFragments
                                                                       error:&error];
                    }
                    success(jsonObject);
                }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (fail && error != nil) {
                fail(error);
            }
        }];
}


//+ (void)JSONDataToDictionaryNeedUTF8EncodeingWithUrl:(NSString *)url
//                          dictinory:(NSDictionary *)dictionary
//                            success:(void (^)(id data))success
//                               fail:(void (^)(NSError *error))fail
//{
//    AFHTTPRequestOperationManager *manager = [ABTools managerwithURL:url];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    
//    [manager POST:url parameters:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        if (success) {
//            
//            NSData *doubi = responseObject;
//            NSString *shabi =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
//            
//           NSString *str1 = [self getUsefulStringWithString:shabi];
//            NSData *data1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
//            
//            NSError *error = nil;
//            id jsonObject = [NSJSONSerialization JSONObjectWithData:data1
//                                                            options:NSJSONReadingAllowFragments
//                                                              error:&error];
//            if ([[jsonObject objectForKey:@"TSR_MSG"] isEqualToString:@"未登陆"] || [[jsonObject objectForKey:@"TSR_MSG"] isEqualToString:@"未登录"]) {
//                [CCTools goBackToLoginView];
//            }else{
//                success(jsonObject);
//            }
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        if (fail && error != nil) {
//            fail(error);
//        }
//    }];
//}


//+(void)showToastView:(NSString *)message onView:(UIView *)view
//{
//    __block MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:view];
//    [view addSubview:HUD];
//    HUD.labelText = message;
//    HUD.mode = MBProgressHUDModeText;
//    
//    //指定距离中心点的X轴和Y轴的位置，不指定则在屏幕中间显示
//    //    HUD.yOffset = 100.0f;
//    //    HUD.xOffset = 100.0f;
//    
//    [HUD showAnimated:YES whileExecutingBlock:^{
//        sleep(1);
//    } completionBlock:^{
//        [HUD removeFromSuperview];
//        //        [HUD release];
//        HUD = nil;
//    }];
//}


//
//
//+(void)pauseLayer:(UIView *)view
//{
//    CFTimeInterval pausedTime = [view.layer convertTime:CACurrentMediaTime() fromLayer:nil];
//    view.layer.speed = 0.0;
//    view.layer.timeOffset = pausedTime;
//}
//
//+(void)resumeLayer:(UIView *)view
//{
//        CFTimeInterval pausedTime = [view.layer timeOffset];
//        view.layer.speed = 1.0;
//        view.layer.timeOffset = 0.0;
//        view.layer.beginTime = 0.0;
//        CFTimeInterval timeSincePause = [view.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
//        view.layer.beginTime = timeSincePause;
//}
//
////图片旋转开始
//+(void) addAnimationWithView:(UIView *)view
//{
//    //添加旋转动画
//    CABasicAnimation* rotationAnimation;
//    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
//    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
//    rotationAnimation.duration = 1;
//    rotationAnimation.cumulative = NO;
//    rotationAnimation.repeatCount = 100000;
//    [view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
//    [self resumeLayer:view];
//}
//
//+(void)stopAnimationWithView:(UIView *)view
//{
//    [self pauseLayer:view];
//    [view.layer removeAnimationForKey:@"rotationAnimation"];
//}
//
//+(void)resumeAnimationWithView:(UIView *)view
//{
//    
//    [self resumeLayer:view];
//}
//
//+(void)ASIRequestWithUrl:(NSString *)url
//                   value:(NSArray *)valueArray
//          finishSelector:(SEL)finishSelector
//            failSelector:(SEL)failSelector
//              requsetTag:(int)tag
//                delegate:(id)delegate
//{
//    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
//    request.tag = tag;
//    [request setUploadProgressDelegate:delegate];
//    [request setDelegate:delegate];
//    [request setTimeOutSeconds:30];
//    [request setRequestMethod:@"POST"];
//    [request setShowAccurateProgress:YES];
//    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
//    
//    if (valueArray.count > 0) {
//        for (NSDictionary *temp in valueArray) {
//            [request setPostValue:[temp allValues][0] forKey:[temp allKeys][0]];
//        }
//    }
//
//    [request setShouldContinueWhenAppEntersBackground:YES];
//    [request setDidFailSelector:failSelector];
//    [request setDidFinishSelector:finishSelector];
//    [request startAsynchronous];
//}
//
//+(void)ASISynchRequestWithUrl:(NSString *)url
//                   value:(NSArray *)valueArray
//          finishSelector:(SEL)finishSelector
//            failSelector:(SEL)failSelector
//              requsetTag:(int)tag
//                delegate:(id)delegate
//{
//    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
//    request.tag = tag;
//    [request setUploadProgressDelegate:delegate];
//    [request setDelegate:delegate];
//    [request setTimeOutSeconds:30];
//    [request setRequestMethod:@"POST"];
//    [request setShowAccurateProgress:YES];
//    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
//    
//    if (valueArray.count > 0) {
//        for (NSDictionary *temp in valueArray) {
//            [request setPostValue:[temp allValues][0] forKey:[temp allKeys][0]];
//        }
//    }
//    
//    [request setShouldContinueWhenAppEntersBackground:YES];
//    [request setDidFailSelector:failSelector];
//    [request setDidFinishSelector:finishSelector];
//    [request startSynchronous];
//}
//
+(NSString *)jsonpTojson:(NSString *)responseString
{
    if ([responseString rangeOfString:@"("].location!=NSNotFound)
    {
        responseString = [responseString componentsSeparatedByString:@"("][1];
        if ([responseString rangeOfString:@")"].location!=NSNotFound)
        {
            responseString = [responseString componentsSeparatedByString:@")"][0];
        }
    }
    return responseString;
}

+(void)setCustomObjToUserDefault:(id)object key:(NSString *)key
{
    NSData *data = [NSKeyedArchiver  archivedDataWithRootObject:object];
    [self setUserDefault:data key:key];
}

+(id)getCustomObjFromUserDefault:(NSString *)key
{
    NSData *data = [CCTools getUserDefault:key];
    return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

+(void)setUserDefault:(id)object key:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:object forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+(id)getUserDefault:(NSString *)key
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

//+(void)removeUserDefault:(NSString *)key
//{
//    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
//}
//
//
//+(NSString *)getUsefulStringWithString:(NSString *)string
//{
//    NSArray *arr = [string componentsSeparatedByString:@"("];
//    
//    return [arr[1] componentsSeparatedByString:@")"][0];
//}
//
////image转换成base64
//+(NSString *)changeImageToBase64:(UIImage *)image
//{
////    NSData *mydata=UIImageJPEGRepresentation(image , 0.4);
////    
////    NSString *pictureDataString=[mydata base64Encoding];
////    
////    return pictureDataString;
//    
//    NSData *imageData = nil;
//    NSString *mimeType = nil;
//    
//    if ([self imageHasAlpha: image]) {
//        imageData = UIImagePNGRepresentation(image);
//        mimeType = @"image/png";
//    } else {
//        imageData = UIImageJPEGRepresentation(image, 1.0f);
//        mimeType = @"image/jpeg";
//    }
//    
//    return [imageData base64EncodedStringWithOptions: 0];
//}
//
//
//+ (BOOL) imageHasAlpha: (UIImage *) image
//{
//    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
//    return (alpha == kCGImageAlphaFirst ||
//            alpha == kCGImageAlphaLast ||
//            alpha == kCGImageAlphaPremultipliedFirst ||
//            alpha == kCGImageAlphaPremultipliedLast);
//}
//
//+(NSString *)mutileImageChangeToBase64:(NSData *)data
//{
//    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//    return encodedImageStr;
//}
//
//
////base64转换成image
//+(UIImage *)changeBase64ToImage:(NSString *)encodedImageStr
//{
//    //Base64字符串转UIImage图片：
//    NSData *decodedImageData = [[NSData alloc]
//                                initWithBase64EncodedString:encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
//    UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
//    return decodedImage;
//}
//
//+(NSString *)mergeStringInArray:(NSArray *)array withString:(NSString *)string
//{
//    NSString *str;
//    for (int i = 0; i < array.count; i++) {
//        if (i == 0) {
//            str = [NSString stringWithFormat:@"%@%@",array[i],string];
//        }else if (i == array.count - 1) {
//            str = [NSString stringWithFormat:@"%@%@",str,array[i]];
//        }else{
//        str = [NSString stringWithFormat:@"%@%@%@",str,array[i],string];
//        }
//    }
//    return str;
//}
//
//
////alaseet转缩略图
//+(UIImage *)getImageWithAsset:(ALAsset *)asset
//{
//    if ([asset isKindOfClass:[ALAsset class]]) {
//        return [UIImage imageWithCGImage:[asset thumbnail]];
//    }else if([asset isKindOfClass:[UIImage class]]){
//        return (UIImage *)asset;
//    }
//    return nil;
//
//}
//
////获取本地当前版本号
//+(NSString *)getLocalVersion
//{
//    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//    return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
//}
//
//+(BOOL)isPhoneNumIllagealWithPhoneNum:(NSString *)phoneNum
//{   BOOL count = NO;
//    BOOL prefix = NO;
//    BOOL allNum = NO;
//    //11位
//    if (phoneNum.length == 11) {
//        count = YES;
//    }
//    //1开头
//    if ([phoneNum hasPrefix:@"1"]) {
//        prefix = YES;
//    }
//    //全数字
//    unichar c;
//    for (int i=0; i<phoneNum.length; i++) {
//        c=[phoneNum characterAtIndex:i];
//        if (!isdigit(c)) {
//            allNum = NO;
//        }
//    else{
//       allNum = YES;
//    }
//    }
//    
//    if (count && prefix && allNum) {
//        return YES;
//    }
//    return NO;
//
//}
//
//+(NetworkStatus)getCurrentReachabilityStatus
//{
//    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
//    switch ([r currentReachabilityStatus]) {
//        case NotReachable:
//            // 没有网络连接
//            return NotReachable;
//            break;
//        case ReachableViaWWAN:
//            // 使用3G网络
//            return ReachableViaWWAN;
//            break;
//        case ReachableViaWiFi:
//            // 使用WiFi网络
//            return ReachableViaWiFi;
//            break;
//        case ReachableVia2G:
//            // 使用WiFi网络
//            return ReachableVia2G;
//            break;
//        case ReachableVia3G:
//            // 使用WiFi网络
//            return ReachableVia3G;
//            break;
//    }
//}
//
//+(NetworkStatus)getServiceReachabilityStatus
//{
//    Reachability *r = [Reachability reachabilityWithHostName:@"http://61.160.137.196:18001/zsdxpt/"];
//    switch ([r currentReachabilityStatus]) {
//        case NotReachable:
//            // 没有网络连接
//            return NotReachable;
//            break;
//        case ReachableViaWWAN:
//            // 使用3G网络
//            return ReachableViaWWAN;
//            break;
//        case ReachableViaWiFi:
//            // 使用WiFi网络
//            return ReachableViaWiFi;
//            break;
//        case ReachableVia2G:
//            // 使用WiFi网络
//            return ReachableVia2G;
//            break;
//        case ReachableVia3G:
//            // 使用WiFi网络
//            return ReachableVia3G;
//            break;
//    }
//}
//
//
//+(int)getNumOfRowInAppAreaViewWithAppCount:(int)count
//{
//    int a = count/4;
//    int b = count%4;
//    if (b == 0) {
//        return a;
//    }else{
//        return a + 1;
//    }
//    
//}
//
////读取头像照片
//+(void)saveHeaderImage:(UIImage *)image
//{
//    NSData *tempData = [CCTools getUserDefault:@"headImageData"];
//    if (tempData) {
//        [CCTools removeUserDefault:@"headImageData"];
//    }
//    
//    NSData *imageData = UIImagePNGRepresentation(image);
//    [CCTools setUserDefault:imageData key:@"headImageData"];
//    
//    
////    BOOL success;
////    NSFileManager *fileManager = [NSFileManager defaultManager];
////    NSError *error;
////    
////    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
////    NSString *documentsDirectory = [paths objectAtIndex:0];
////    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
////    NSLog(@"imageFile->>%@",imageFilePath);
////    success = [fileManager fileExistsAtPath:imageFilePath];
////    if(success) {
////        success = [fileManager removeItemAtPath:imageFilePath error:&error];
////    }
////    [UIImageJPEGRepresentation(image, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
//
//}
//
//+(UIImage *)readHeaderImage
//{
////    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
////    NSString *documentsDirectory = [paths objectAtIndex:0];
////    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
////    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
////    return selfPhoto;
//    
//    NSData *imageData = [CCTools getUserDefault:@"headImageData"];
//    UIImage *image = [UIImage imageWithData: imageData];
//    return image;
//}
//
////+(void)addViewWhenLoadingOnView:(UIView *)view
////{
////    CGRect frame = view.frame;
////    UIView *view = [UIView alloc]initWithFrame:frame;
////}
//
//
//+(NSString *)getLocalTime
//{
//    NSDate *  senddate=[NSDate date];
//    
//    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
//    
//    [dateformatter setDateFormat:@"YYYYMMdd"];
//    
//    NSString *  locationString=[dateformatter stringFromDate:senddate];
//    
//    return locationString;
//}
//
//+(NSString *)getLocalWeek
//{
//    NSString *week;
//    NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
//    NSInteger weekday = [componets weekday];
//    
//    switch (weekday) {
//        case 1:
//            week = @"星期日";
//            break;
//        case 2:
//            week = @"星期一";
//            break;
//        case 3:
//            week = @"星期二";
//            break;
//        case 4:
//            week = @"星期三";
//            break;
//        case 5:
//            week = @"星期四";
//            break;
//        case 6:
//            week = @"星期五";
//            break;
//        case 7:
//            week = @"星期六";
//            break;
//        default:
//            break;
//    }
//    return week;
//}
//
//+(void)goBackToLoginView
//{
//    AppDelegate *appdelegate = [AppDelegate currentAppDelegate];
//    [appdelegate.sideSlipVC dismissViewControllerAnimated:YES completion:^{
//        appdelegate.sideSlipVC = nil;
//    }];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"kNoticeExitAccount" object:nil];
//}
//
//+(NSString *)jsonString:(NSDictionary *)dict
//{
//    NSData *jsonData = [CCTools toJSONData:dict];
//    
//    NSString *jsonString = [[NSString alloc] initWithData:jsonData
//                                                 encoding:NSUTF8StringEncoding];
//    return jsonString;
//}
//
//
//+ (NSData *)toJSONData:(id)theData{
//    
//    NSError *error = nil;
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
//                                                       options:NSJSONWritingPrettyPrinted
//                                                         error:&error];
//    
//    if ([jsonData length] > 0 && error == nil){
//        return jsonData;
//    }else{
//        return nil;
//    }
//}


@end
